import 'package:flutter/material.dart';
import 'package:flutter_mark_trip/dao/home_dao.dart';
import 'package:flutter_mark_trip/model/common_model.dart';
import 'package:flutter_mark_trip/model/grid_nav_model.dart';
import 'package:flutter_mark_trip/model/home_model.dart';
import 'package:flutter_mark_trip/model/sales_box_model.dart';
import 'package:flutter_mark_trip/pages/Search_Page.dart';
import 'package:flutter_mark_trip/pages/Speak_Page.dart';
import 'package:flutter_mark_trip/util/navigator_util.dart';
import 'package:flutter_mark_trip/widget/gird_nav.dart';
import 'package:flutter_mark_trip/widget/local_nav.dart';
import 'package:flutter_mark_trip/widget/sales_box.dart';
import 'package:flutter_mark_trip/widget/search_bar.dart';
import 'package:flutter_mark_trip/widget/sub_nav.dart';
import 'package:flutter_mark_trip/widget/webview.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_mark_trip/widget/loading_container.dart';
import 'package:flutter_splash_screen/flutter_splash_screen.dart';

const APPBAR_SCROLL_OFFSET = 100;
const SEARCH_BAR_DEFAULT_TEXT = "网红打卡地 景点 酒店 美食";

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  //透明度
  double appBarAlpha = 0;
  List<CommonModel> bannerList = [];
  List<CommonModel> localNavList = [];
  List<CommonModel> subNavList = [];
  GridNavModel gridNavModel;
  SalesBoxModel salesBoxModel;
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _handleRefresh();
    hideScreen();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff2f2f2),
      //去除顶部状态栏
      body: LoadingContainer(
          isLoading: _loading,
          child: Stack(
            children: <Widget>[
              MediaQuery.removePadding(
                context: context,
                removeTop: true,
                child: RefreshIndicator(
                  child: NotificationListener(
                    onNotification: (scrollNotification) {
                      //过滤掉无效的滑动
                      if (scrollNotification is ScrollUpdateNotification &&
                          scrollNotification.depth == 0) {
                        _onScroll(scrollNotification.metrics.pixels);
                      }
                      return false;
                    },
                    child: _getListView,
                  ),
                  onRefresh: _handleRefresh,
                ),
              ),
              _appBar,
            ],
          )),
    );
  }

  //监听滚动设置AppBar的透明度
  void _onScroll(double offset) {
    double alpha = offset / APPBAR_SCROLL_OFFSET;
    if (alpha < 0) {
      alpha = 0;
    } else if (alpha > 1) {
      alpha = 1;
    }
    setState(() {
      appBarAlpha = alpha;
    });
//    print(appBarAlpha);
  }

  Future<Null> _handleRefresh() async {
    ///方式一
    /*HomeDao.fetch().then((result){
      setState(() {
        resultString = json.encode(result);
      });
    }).catchError((e){
      setState(() {
        resultString = e.toString()
      });
    });*/

    ///方式二
    try {
      HomeModel homeModel = await HomeDao.fetch();
      setState(() {
        bannerList = homeModel.bannerList;
        localNavList = homeModel.localNavList;
        gridNavModel = homeModel.gridNav;
        subNavList = homeModel.subNavList;
        salesBoxModel = homeModel.salesBox;
        _loading = false;
      });
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
    return null;
  }

  Widget get _getListView {
    return ListView(
      children: <Widget>[
        _banner,
        Column(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
              child: LocalNav(
                localNavList: localNavList,
              ),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
              child: GridNav(
                gridNavModel: gridNavModel,
              ),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
              child: SubNav(
                subNavList: subNavList,
              ),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(7, 4, 7, 4),
              child: SalesBox(
                salesBox: salesBoxModel,
              ),
            ),
          ],
        )
      ],
    );
  }

  //AppBar
  Widget get _appBar {
    /*return Opacity(
      opacity: appBarAlpha,
      child: Container(
        height: 80,
        decoration: BoxDecoration(color: Colors.white),
        child: Center(
          child: Padding(
            padding: EdgeInsets.only(top: 20),
            child: Text("首页"),
          ),
        ),
      ),
    );*/
    return Column(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
              gradient: LinearGradient(
            //AppBar渐变遮罩背景
            colors: [Color(0x66000000), Colors.transparent],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          )),
          child: Container(
            padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
            height: 80.0,
            decoration: BoxDecoration(
              color: Color.fromARGB((appBarAlpha * 255).toInt(), 255, 255, 255),
            ),
            child: SearchBar(
              searchBarType: appBarAlpha > 0.2
                  ? SearchBarType.homeLight
                  : SearchBarType.home,
              inputBoxClick: _jumpToSearch,
              speakClick: _jumpToSpeak,
              defaultText: SEARCH_BAR_DEFAULT_TEXT,
              leftButtonClick: () {},
            ),
          ),
        ),
        //阴影
        Container(
          height: appBarAlpha > 0.2 ? 0.5 : 0,
          decoration: BoxDecoration(
              boxShadow: [BoxShadow(color: Colors.black12, blurRadius: 0.5)]),
        )
      ],
    );
  }

  //  banner
  Widget get _banner {
    return Container(
      height: 180,
      child: Swiper(
        itemCount: bannerList.length,
        autoplay: true,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () {
              //Banner点击跳转
              NavigatorUtil.push(
                context,
                WebView(
                  url: bannerList[index].url,
                  title: '活动',
                ),
              );
            },
            child: Image.network(
              bannerList[index].icon,
              fit: BoxFit.fill,
            ),
          );
        },
        pagination: SwiperPagination(),
      ),
    );
  }

  _jumpToSearch() {
    NavigatorUtil.push(
        context,
        SearchPage(
          hideLeft: false,
          hint: SEARCH_BAR_DEFAULT_TEXT,
        ));
  }

  _jumpToSpeak() {
    NavigatorUtil.push(context, SpeakPage());
  }

  ///hide your splash screen
  Future<void> hideScreen() async {
    Future.delayed(Duration(milliseconds: 1500), () {
      FlutterSplashScreen.hide();
    });
  }
}
